package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go-web-app-demo/common"
	internalValidator "go-web-app-demo/pkg/validator"
	"go-web-app-demo/router"
	"go-web-app-demo/service"
	"net/http"
)

func init() {
	router.AddHandler(&router.Handler{
		Method:       "post",
		RelativePath: "/post/vote",
		HandleFunc:   PostVote,
		NeedAuth:     false,
	})
}

func PostVote(c *gin.Context) {

	vr := new(service.VoteReq)
	if err := c.ShouldBindJSON(vr); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		var msg interface{}
		if !ok {
			msg = err.Error()
		} else {
			msg = internalValidator.RemoveTopStruct(errs.Translate(internalValidator.Trans))
		}

		c.JSON(http.StatusBadRequest, common.NewFailed(msg))
		return
	}

	// demo 代码随便传一个
	vr.UserID = 1
	c.JSON(http.StatusOK, service.PostVote(vr))

}
